import React, {useEffect, useRef, useState} from "react";
import {Alert, Button, Col, Icon, Input, Row} from "antd";
import PropTypes from 'prop-types';
import useKeyPress from "../hooks/useKeyPress";

const FileSearch = ({title, onFileSearch}) => {
    const [inputActive, setInputActive] = useState(false);
    const [value, setValue] = useState('');
    const enterPressed = useKeyPress(13);
    const escPressed = useKeyPress(27);
    let node = useRef(null);

    const closeSearch = () => {
        setInputActive(false);
        setValue('');
    };

    // 键盘监听
    useEffect(() => {
        if (enterPressed && inputActive) {
            onFileSearch(value)
        } else if (escPressed && inputActive) {
            closeSearch();
        }
    });

    useEffect(() => {
        if (inputActive) {
            node.current.focus();
        }
    }, [inputActive]);

    return (
        <div>
            <Alert message={
                <Row type="flex" justify="space-between" align="middle">
                    <Col span={18}>
                        {
                            !inputActive
                                ? <span>{title}</span>
                                : <Input
                                    placeholder="search file"
                                    ref={node}
                                    onChange={(e) => {
                                        setValue(e.target.value)
                                    }}
                                />
                        }
                    </Col>
                    <Col span={1}/>
                    <Col span={5}>
                        <Button
                            type="primary"
                            onClick={ ()=> {
                                setInputActive(!inputActive)
                            } }
                        >
                            {
                                !inputActive
                                    ? <Icon type="search" />
                                    : <Icon type="close" />
                            }
                        </Button>
                    </Col>
                </Row>} type="success"/>
        </div>
    )
};

// 属性检查
FileSearch.prototype = {
    title: PropTypes.string,
    onFileSearch: PropTypes.func.isRequired
};

// 属性默认值
FileSearch.defaultProps = {
    title: '我的云文档'
};

export default FileSearch;
